import { reqSendCode, reqUserRegister, reqUserLogin, reqUserInfo,reqUserLogout } from "@/api";
import { getToken, setToken,clearToken } from '@/utils/token'
const actions = {
  async getCode({ commit }, phone) {
    let res = await reqSendCode(phone);
    if (res.code == 200) {
      commit("GET_CODE", res.data);
    } else {
      return Promise.reject(new Error(res.message));
    }
  },
  async getUserRegister({ commit }, userInfo) {
    let res = await reqUserRegister(userInfo);

    if (res.code == 200) {
      // commit("USER_REGISTER_SUCCESS",res.data);
    } else {
      return Promise.reject(new Error(res.message));
    }
  },
  // 登录【token】
  async userLogin({ commit }, userInfo) {
    let res = await reqUserLogin(userInfo);
    if (res.code == 200) {
      // 存储一下token
      commit("USER_LOGIN", res.data.token);
    } else {
      return Promise.reject(new Error(res.message));
    }
  },
  async userInfo({ commit }) {
    let res = await reqUserInfo();
    if (res.code == 200) {
      // 存一下
      commit('USER_INFO', res.data);
      return 'OK';
    }else {
      return Promise.reject(new Error(res.message));
    }
  },
  async userLogout({ commit }){
    let res = await reqUserLogout();
    if(res.code == 200) {
      commit('USER_LOGOUT');
      return 'ok';
    }else {
      return Promise.reject(new Error(res.message));
    }
  },

};
const mutations = {
  GET_CODE(state, code) {
    state.code = code;
  },
  USER_LOGIN(state, token) {
    state.token = token;
    // 持久化存储
    setToken(token);
  },
  USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  USER_LOGOUT(state){
    state.token = '';
    state.userInfo = {};
    clearToken();
  }
};
const state = {
  code: '',
  token: getToken(),
  userInfo: {},
};
const getters = {
  userInfo(state){
    return state.userInfo || {};
  }
};
export default {
  namespaced: true,
  actions,
  mutations,
  state,
  getters,
}